<template>
	<!-- 刮一刮 -->
	<view class="shave_box"  :style="{width:widthCanvas+'rpx',height:heightCanvas+'rpx'}">
		<image  :style="{width:widthCanvas+'rpx',height:heightCanvas+'rpx'}" v-if="gdata.type=='image'" class="shaveImg" :src="gdata.content"></image>
		<view   :style="{width:widthCanvas+'rpx',height:heightCanvas+'rpx'}" v-if="gdata.type=='text'" class="shaveTxt"><span>{{gdata.content}}</span></view>
		<canvas class="canvas" :style="{width:widthCanvas+'rpx',height:heightCanvas+'rpx'}" @touchstart="start" @touchend="end" @touchmove="move" v-if="!clearAll" canvas-id="canvasA" id="canvasA"></canvas>
	</view>

</template>

<script>
	export default {
		props:{
			gdata:{
				type:Object,
				default:()=>{return{}}
			},
			isInit:{
				type:Boolean,
				default:false
			},
			isAllow:{
				type:Boolean,
				default:true
			},
			widthCanvas:{
				default:590
			},
			heightCanvas:{
				default:270
			}
		},
		data() {
			return {
				clearAll:false,
				stepClear:1,
				fisrtTouch:0
			};
		},
		methods: {
			//绘制|重置或绘制canvas内容
			initDrawCanvas(){
				this.clearAll = false;
				this.$nextTick(()=>{
					const query = uni.createSelectorQuery().in(this);
					//设置初始化
					query.select('#canvasA').boundingClientRect(data => {
					  let width = data.width;
					  let height = data.height;
					  this.init({
					  	canvasId: 'canvasA',
					  	regionPer: 30,
						width:width,
						height:height,
						size:12,
					  });
					}).exec()
				})
			},
			//绑定的手指移动事件
			start(e) {
				this.$emit('start')
				this.eraser(e);
			},
			move(e) {
				this.eraser(e);
				// this.fisrtTouch++
				// if(this.fisrtTouch==1){
				// 	let _this = this
				// 	setTimeout(()=>{
				// 		_this.$emit('startTouch')
				// 	},300)
				// }
			},
			end(e) {
				this.getFilledPercentage().then((data)=>{
					if(parseInt(data) >= this.regionPer) {
						//刮的区域大于等于设定的值就清除canvas
						this.clearAll = true;
						this.fisrtTouch++
						if(this.fisrtTouch==1){
							let _this = this
							setTimeout(()=>{
								_this.$emit('startTouch')//刮刮卡的 刮卡逻辑
							},300)
						}
						if (this.clearAll) {
							this.ctx.clearRect(0, 0, this.width, this.height);
							this.ctx.draw();
							this.$emit('finish')
						}
					}
				})
			},
			//初始化参数信息
			init(opts) {
				opts = opts || {};
				this.canvasId = opts.canvasId || 'canvasId';
				this.width = opts.width || 550;//宽默认为刮区200px
				this.height = opts.height || 825;//高默认刮区100px
				this.maskColor = opts.maskColor || '#000000';//刮区蒙版颜色
				this.rw =  14;//刮
				this.regionPer = opts.regionPer || 90;//清除区域百分比| 默认刮了90%清除全部蒙版
				this.clearAll = false;
				this.ctx = uni.createCanvasContext(this.canvasId, this);
				this.drawMask();
				this.fisrtTouch=0
			},
			//填充内容蒙版————绘制的内容 | 这块可自己自由发挥修改(ps其它逻辑可以完全不变)
			drawMask() {
				//绘制文字
				// this.ctx.setFillStyle(this.maskColor);
				// this.ctx.fillRect(0, 0, this.width, this.height);
				// this.ctx.setFontSize(20)
				// this.ctx.setFillStyle('#C3C3C0')
				// this.ctx.fillText('刮一下', 20, 20)
				//绘制图案
				this.ctx.drawImage(require('@/static/guess/gua.png'), 0, 0, uni.upx2px(590), uni.upx2px(270))
				this.ctx.draw();
			},
			//清除轨迹
			eraser(e) {
				if(!this.isAllow)
					return
				let x = e.touches[0].x,
					y = e.touches[0].y;
				// this.ctx.clearRect(x, y, this.rw, this.rw);
				this.clearArc(x,y,this.rw)
				this.stepClear = 1
				this.ctx.draw(true);
			},
			//画一个圆
			clearArc(x, y, radius) {
				var calcWidth = radius - this.stepClear;
				var calcHeight = Math.sqrt(radius * radius - calcWidth * calcWidth);
				var posX = x - calcWidth;
				var posY = y - calcHeight;
				var widthX = 2 * calcWidth;
				var heightY = 2 * calcHeight;
				if (this.stepClear <= radius) {
					this.ctx.clearRect(posX, posY, widthX, heightY);
					this.stepClear += 1;
					this.clearArc(x, y, radius);
				}
			},
			//计算清除的百分占比
			getFilledPercentage() {
				const fillePercent= new Promise((resolve) => {
					uni.canvasGetImageData({
						canvasId:this.canvasId,
						x:0,
						y:0,
						width:this.width,
						height:this.height,
						success: (res) =>{
							// res.data是个数组，存储着指定区域每个像素点的信息，数组中4个元素表示一个像素点的rgba值
							let pixels = res.data;
							let transPixels = [];
							for(let i = 0; i < pixels.length; i += 4) {
								// 严格上来说，判断像素点是否透明需要判断该像素点的a值是否等于0，
								// 为了提高计算效率，这儿设置当a值小于128，也就是半透明状态时就可以了
								if(pixels[i + 3] < 128) {
									transPixels.push(pixels[i + 3]);
								}
							}
							resolve((transPixels.length / (pixels.length / 4) * 100).toFixed(2))
						}
					})
				})
				return fillePercent
			}
		},
		created() {
			this.$nextTick(()=>{
				this.initDrawCanvas()
			})
		},
		watch:{
			isInit:{
				handler(newval,oldval){
					if(newval==true){
						this.initDrawCanvas()
					}
				},
				deep:true
			}
		}
	}
</script>

<style>
			.shave_box{
				width:590rpx;
				height:270rpx;
				position:relative;
			}
			.shaveImg{
				width:590rpx;
				height:270rpx;
				line-height:270rpx;
				color:#999999;;
				text-align:center;
				font-size:36rpx;
				letter-spacing:0rpx;
				z-index:8;
			}
			.shaveTxt{
				width:  590rpx;
				height : 270rpx;
				line-height:  270rpx;
				color:  #999999;
				text-align: center;
				font-size: 36rpx;
				letter-spacing: 0rpx;
				z-index: 8;
				white-space: normal;
			}
			.canvas{
				width : 590rpx;
				height : 270rpx;
				position: absolute;
				left: 0;
				top: 0;
				z-index: 9;
			}


</style>
